package cn.zhj.springboot.interceptor;

import cn.zhj.springboot.config.AuthProperties;
import cn.zhj.springboot.filter.MyFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Autowired
    private MyInterceptor myInterceptor;

    @Autowired
    private AuthProperties authProperties;

    /**
     * 注册拦截器
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(myInterceptor)
                .addPathPatterns("/**")         // 拦截所有请求
                .excludePathPatterns(authProperties.getExcludePaths());
        //已用配置文件替代
//                .excludePathPatterns("/user/doLogin");  // 排除登录接口
    }

    /**
     * 注册过滤器（Java Config 方式）
     * 注意：如果使用 @Component 或 XML 注册 Filter，也可以不在此处注册
     */
    // 如果你使用的是 Spring Boot，并通过 FilterRegistrationBean 注册，可以如下方式：
    @Bean
    public FilterRegistrationBean<MyFilter> registerMyFilter(MyFilter myFilter) {
        FilterRegistrationBean<MyFilter> registration = new FilterRegistrationBean<>();
        registration.setFilter(myFilter);
        registration.addUrlPatterns("/*");           // 拦截所有请求
        //已用配置文件替代
//        registration.addInitParameter("excludedUrls", "/path1,/path2");
        registration.setName("myFilter");
        registration.setOrder(1);                    // 设置执行顺序
        return registration;
    }

}
